﻿
// DcmImageDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "DcmImage.h"
#include "DcmImageDlg.h"
#include "afxdialogex.h"
#include "Utilities.h"
#include "DcmParser.h"

#include <shlobj.h>  // 包含SHBrowseForFolder等声明
#pragma comment(lib, "shell32.lib")  // 链接shell32库

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CDcmImageDlg 对话框



CDcmImageDlg::CDcmImageDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DCMIMAGE_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDcmImageDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_DCM, m_list);
	DDX_Control(pDX, IDC_STATIC_DISPLAY, m_disp);
}

BEGIN_MESSAGE_MAP(CDcmImageDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_FILE, &CDcmImageDlg::OnBnClickedButtonFile)
	ON_BN_CLICKED(IDC_BUTTON_DIR, &CDcmImageDlg::OnBnClickedButtonDir)
	ON_BN_CLICKED(IDC_BUTTON_CLEARFILE, &CDcmImageDlg::OnBnClickedButtonClearfile)
	ON_LBN_SELCHANGE(IDC_LIST_DCM, &CDcmImageDlg::OnSelchangeListDcm)
	ON_BN_CLICKED(IDC_BUTTON_PREV, &CDcmImageDlg::OnBnClickedButtonPrev)
	ON_BN_CLICKED(IDC_BUTTON_NEXT, &CDcmImageDlg::OnBnClickedButtonNext)
	ON_BN_CLICKED(IDC_BUTTON_PREV_FRAME, &CDcmImageDlg::OnBnClickedButtonPrevFrame)
	ON_BN_CLICKED(IDC_BUTTON_NEXT_FRAME, &CDcmImageDlg::OnBnClickedButtonNextFrame)
	ON_WM_SIZE()
	ON_BN_CLICKED(IDC_BUTTON_EXP_JPG, &CDcmImageDlg::OnBnClickedButtonExpJpg)
	ON_BN_CLICKED(IDC_BUTTON_EXP_PNG, &CDcmImageDlg::OnBnClickedButtonExpPng)
	ON_BN_CLICKED(IDC_BUTTON_EXP_TIFF, &CDcmImageDlg::OnBnClickedButtonExpTiff)
	ON_BN_CLICKED(IDC_BUTTON_EXP_VIDEO, &CDcmImageDlg::OnBnClickedButtonExpVideo)
	ON_BN_CLICKED(IDC_BUTTON_EXP_BMP, &CDcmImageDlg::OnBnClickedButtonExpBmp)
END_MESSAGE_MAP()


// CDcmImageDlg 消息处理程序

BOOL CDcmImageDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	DcmParser::RegistryCodecs();
	
	m_nListWidth = m_nDefWidth = m_list.GetHorizontalExtent();

	GetDlgItem(IDC_BUTTON_EXP_VIDEO)->EnableWindow(FALSE);
	GetDlgItem(IDC_BUTTON_PREV_FRAME)->EnableWindow(FALSE);
	GetDlgItem(IDC_BUTTON_NEXT_FRAME)->EnableWindow(FALSE);
	
	Arrange();

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CDcmImageDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CDcmImageDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CDcmImageDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CDcmImageDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);

	// TODO: 在此处添加消息处理程序代码
	if (::IsWindow(m_list.m_hWnd)) {
		Arrange();
	}
}


void CDcmImageDlg::OnBnClickedButtonFile()
{
	CString strFilter;
	strFilter = _T("DCM file(*.dcm;*.dic)|*.dcm;*.dic|All files(*.*)|*.*||");
	CFileDialog dlg(TRUE, NULL, NULL,
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT,
		strFilter, NULL);

	TCHAR *pszFile = new TCHAR[MAX_PATH * 500];
	memset(pszFile, 0, sizeof(TCHAR)*MAX_PATH * 500);
	dlg.m_ofn.lpstrFile = pszFile;
	dlg.m_ofn.nMaxFile = MAX_PATH * 500;
	dlg.m_ofn.lpstrFile[0] = '\0';

	//m_lstFile.ResetContent();
	//m_vecDcmFile.clear();

	if (dlg.DoModal() == IDOK)
	{
		CString strFile;
		POSITION pos = dlg.GetStartPosition();
		while (pos != NULL)
		{
			strFile = dlg.GetNextPathName(pos);
			m_vecDcmFile.push_back(strFile);
			m_list.AddString(strFile);
			UpdateWidth(strFile);
		}

		CString txt;
		txt.Format(_T("DICOM文件  数量: %d"), m_list.GetCount());
		GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
	}

	delete[] pszFile;
}


void CDcmImageDlg::OnBnClickedButtonDir()
{
	CFolderPickerDialog dlg(m_lastDir);
	if (dlg.DoModal() == IDOK)
	{
		CString dir = dlg.GetPathName();
		m_lastDir = dir;

		if (m_lastDir.Right(1) != _T("\\"))
			m_lastDir += _T("\\");

		EnumFileInDir(m_lastDir, m_vecDcmFile, _T(".dcm"));
		for (int i = 0; i < m_vecDcmFile.size(); i++)
		{
			m_list.AddString(m_vecDcmFile.at(i));
			UpdateWidth(m_vecDcmFile.at(i));
		}

		CString txt;
		txt.Format(_T("DICOM文件  数量: %d"), m_list.GetCount());
		GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
	}
}


void CDcmImageDlg::OnBnClickedButtonClearfile()
{
	m_list.ResetContent();
	m_list.SetHorizontalExtent(m_nDefWidth);
	m_nListWidth = m_nDefWidth;
	m_vecDcmFile.clear();

	CString txt;
	txt.Format(_T("DICOM文件  数量: 0"));
	GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
}

void CDcmImageDlg::Arrange()
{
	CRect rc;
	GetClientRect(&rc);

	m_list.MoveWindow(10, 70, 300, rc.bottom - 80);
	m_disp.MoveWindow(320, 10, rc.right - 320 - 110, rc.bottom - 20);

	CRect rcBtn;
	GetDlgItem(IDC_BUTTON_PREV)->GetWindowRect(&rcBtn);
	int w = rcBtn.Width();
	int h = rcBtn.Height();

	int btnTop = 50;
	GetDlgItem(IDC_BUTTON_PREV)->MoveWindow(rc.right - w - 10, btnTop, w, h);
	GetDlgItem(IDC_BUTTON_NEXT)->MoveWindow(rc.right - w - 10, btnTop + h + 8, w, h);
	GetDlgItem(IDC_BUTTON_PREV_FRAME)->MoveWindow(rc.right - w - 10, btnTop + 2*(h+8), w, h);
	GetDlgItem(IDC_BUTTON_NEXT_FRAME)->MoveWindow(rc.right - w - 10, btnTop + 3*(h+8), w, h);

	btnTop = 280;
	GetDlgItem(IDC_BUTTON_EXP_JPG)->MoveWindow(rc.right - w - 10, btnTop, w, h);
	GetDlgItem(IDC_BUTTON_EXP_PNG)->MoveWindow(rc.right - w - 10, btnTop + h + 8, w, h);
	GetDlgItem(IDC_BUTTON_EXP_BMP)->MoveWindow(rc.right - w - 10, btnTop + 2 * (h + 8), w, h);
	GetDlgItem(IDC_BUTTON_EXP_TIFF)->MoveWindow(rc.right - w - 10, btnTop + 3 * (h + 8), w, h);
	GetDlgItem(IDC_BUTTON_EXP_VIDEO)->MoveWindow(rc.right - w - 10, btnTop + 4 * (h + 8), w, h);
}

void CDcmImageDlg::UpdateWidth(LPCTSTR lpszItem)
{
	CFont *pFont = m_list.GetFont();
	CClientDC dc(this);
	dc.SelectObject(pFont);
	CSize sz = dc.GetTextExtent(lpszItem, _tcslen(lpszItem));
	sz.cx += (3 * ::GetSystemMetrics(SM_CXBORDER));
	if (sz.cx > m_nListWidth)
	{
		m_nListWidth = sz.cx + 10;
		m_list.SetHorizontalExtent(m_nListWidth);
	}
}

void CDcmImageDlg::EnumFileInDir(CString dir, std::vector<CString>& vec, LPCTSTR ext /*= NULL*/)
{
	CFileFind finder;

	if (dir[dir.GetLength() - 1] != _T('\\')) dir += _T("\\");

	if (finder.FindFile(dir + _T("*.*")))
	{
		BOOL bFind = FALSE;
		do
		{
			bFind = finder.FindNextFile();

			if (finder.IsDots())
				continue;
			else if (finder.IsDirectory())
			{
				CString strDir = finder.GetFilePath();
				strDir += _T("\\");
				EnumFileInDir(strDir, vec, ext);
			}
			else
			{
				CString fnext;
				CString fn = finder.GetFileName();
				int pos = fn.ReverseFind(_T('.'));
				if (pos != -1)
				{
					CString strExt = ext;
					fnext = fn.Mid(pos);
					if (fnext.CompareNoCase(strExt) == 0)
						vec.push_back(finder.GetFilePath());
				}
			}

		} while (bFind);
	}
}


void CDcmImageDlg::OnSelchangeListDcm()
{
	// TODO: 在此添加控件通知处理程序代码
	CString str;
	int idx = m_list.GetCurSel();
	m_list.GetText(idx, str);
	m_disp.LoadFile(str);

	int nFrames = m_disp.GetFrameCount();
	if (nFrames > 1) {
		if (nFrames > 9) {
			GetDlgItem(IDC_BUTTON_EXP_VIDEO)->EnableWindow(TRUE);
		}
		else {
			GetDlgItem(IDC_BUTTON_EXP_VIDEO)->EnableWindow(FALSE);
		}
		GetDlgItem(IDC_BUTTON_PREV_FRAME)->EnableWindow(TRUE);
		GetDlgItem(IDC_BUTTON_NEXT_FRAME)->EnableWindow(TRUE);
	}
	else {
		GetDlgItem(IDC_BUTTON_EXP_VIDEO)->EnableWindow(FALSE);
		GetDlgItem(IDC_BUTTON_PREV_FRAME)->EnableWindow(FALSE);
		GetDlgItem(IDC_BUTTON_NEXT_FRAME)->EnableWindow(FALSE);
	}

	//OutputDebugString(_T("选中:") + str + _T("\r\n"));


}


void CDcmImageDlg::OnBnClickedButtonPrev()
{
	// TODO: 在此添加控件通知处理程序代码
	int idx = m_list.GetCurSel();
	int nCount = m_list.GetCount();
	if (nCount == 0) return;

	if (idx < 0) idx = 1;
	if (idx == 0) {
		return;
	}

	idx--;
	m_list.SetCurSel(idx);
	OnSelchangeListDcm();
}


void CDcmImageDlg::OnBnClickedButtonNext()
{
	int idx = m_list.GetCurSel();
	int nCount = m_list.GetCount();
	if (nCount == 0) return;

	if (idx < 0) idx = 0;
	if (idx == nCount - 1) {
		return;
	}

	idx++;
	m_list.SetCurSel(idx);
	OnSelchangeListDcm();
}


void CDcmImageDlg::OnBnClickedButtonPrevFrame()
{
	m_disp.PrevFrame();
}


void CDcmImageDlg::OnBnClickedButtonNextFrame()
{
	m_disp.NextFrame();
}

CString CDcmImageDlg::SelectFolder()
{
	CString strFolder;
	BROWSEINFO bi = { 0 };
	bi.lpszTitle = _T("请选择文件夹");  // 对话框标题

	// 设置初始目录（可选）
	// TCHAR szInitDir[MAX_PATH] = _T("C:\\");
	// bi.lpfn = BrowseCallbackProc;  // 回调函数用于设置初始目录
	// bi.lParam = (LPARAM)szInitDir;

	// 显示文件夹选择对话框
	LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
	if (pidl != NULL)
	{
		// 将选择的文件夹路径转换为字符串
		TCHAR szPath[MAX_PATH];
		if (SHGetPathFromIDList(pidl, szPath))
		{
			strFolder = szPath;
		}
		// 释放内存
		CoTaskMemFree(pidl);
	}
	return strFolder;
}

void CDcmImageDlg::OnBnClickedButtonExpJpg()
{
	std::string dst = SelectFolder();
	if (!m_disp.Export(dst, 0)) {
		MessageBox(_T("导出JPG失败!"));
	}
}


void CDcmImageDlg::OnBnClickedButtonExpPng()
{
	std::string dst = SelectFolder();
	if (!m_disp.Export(dst, 1)) {
		MessageBox(_T("导出PNG失败!"));
	}
}

void CDcmImageDlg::OnBnClickedButtonExpBmp()
{
	std::string dst = SelectFolder();
	if (!m_disp.Export(dst, 2)) {
		MessageBox(_T("导出BMP失败!"));
	}
}

void CDcmImageDlg::OnBnClickedButtonExpTiff()
{
	std::string dst = SelectFolder();
	if (!m_disp.Export(dst, 3)) {
		MessageBox(_T("导出TIFF失败!"));
	}
}


void CDcmImageDlg::OnBnClickedButtonExpVideo()
{
	std::string dst = SelectFolder();
	if (!m_disp.Export(dst, 4)) {
		MessageBox(_T("导出MP4失败!"));
	}
	else {
		MessageBox(_T("导出MP4完成!"));
	}
}


